//
//  SettingsViewController.m
//  YoucApp
//
//  Created by Liam on 12/1/12.
//
//

#import "SettingsViewController.h"
#import "UserManager.h"
#import "APNSManager.h"
#import "CmnMacro.h"
#import "IASKSettingsReader.h"
#import "IASKSpecifier.h"
#import "IASKPSTitleValueSpecifierViewCell.h"
#import "TSLocateView.h"
#import "UIActionSheet+Modal.h"
#import "UpgradeAlert.h"
#import "SexPickerView.h"
#import "SignPickerView.h"

@interface SettingsViewController ()

@end

@implementation SettingsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	if (!self.delegate)
	{
		self.delegate = self;
	}
	
	self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"wy_setting_bg.png"]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setDefaultValue:(id)value forKey:(NSString *)key
{
	if ([[self.settingsStore objectForKey:key] length] == 0)
	{
		[self.settingsStore setObject:value forKey:key];
	}
}

- (NSString *)displayLocation:(TSLocation *)location
{
	NSString *display = nil;
	if (location && [location.postcode length])
		display = [NSString stringWithFormat:@"%@ %@", location.state, location.city, nil];
	
	return display;
}

- (void)updateUserInfoToSettingStore
{
	[self.settingsStore setObject:[[UserManager instance] getSavedLoginName] forKey:@"details_email"];
	[self.settingsStore setObject:[UserManager instance].userInfo.nickname forKey:@"details_nickname"];
	[self.settingsStore setObject:[UserManager instance].userInfo.sex forKey:@"details_sex"];
	[self.settingsStore setObject:[UserManager instance].userInfo.sign forKey:@"details_sign"];
	[self.settingsStore setObject:[UserManager instance].userInfo.location forKey:@"details_location_postcode"];
	
	NSString *postcode = [UserManager instance].userInfo.location;
	
	TSLocateView *locateView = [[TSLocateView alloc] initWithPostCode:postcode delegate:self];
	
	NSString *display = [self displayLocation:locateView.locate];
	
	[self.settingsStore setObject:display forKey:@"details_location"];
	
	[locateView release];
}

- (void)loadDynamicSettings:(BOOL)animated
{
	if ([self.file isEqualToString:@"Root"])
	{
		[self setHiddenKeys:
		 [UserManager instance].isUserLogined ?
		 [NSSet setWithObjects:@"LoginButton", nil] :
		 [NSSet setWithObjects:@"Personal", @"Notification", @"LogoutButton", nil]
				   animated:animated];
		
		[self updateUserInfoToSettingStore];
		
	}
	else if ([self.file isEqualToString:@"Notification"])
	{
		BOOL isSoundOpened = NO;
		BOOL isAPNSOpened = [[APNSManager instance] isAPNSOpened:&isSoundOpened];
		
		NSString *sValue = isAPNSOpened ? @"Opened" : @"Closed";
		
		sValue = NSLocalizedString(sValue, @"attention_notification_value");
		
		[self.settingsStore setObject:sValue forKey:@"attention_notification_state"];
		[self.settingsStore setBool:isSoundOpened forKey:@"an_type_sound"];
		
		[self setHiddenKeys:isAPNSOpened ? nil : [NSSet setWithObjects:
												  @"an_type_group",
												  @"an_type_sound",
												  @"an_dnd_group",
												  @"an_dnd_open",
												  @"an_dnd_night",
												  nil]
				   animated:animated];
		
	}
	else if ([self.file isEqualToString:@"Personal"])
	{
	}
	else if ([self.file isEqualToString:@"About"])
	{
		[self.settingsStore setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"app_version"];
	}
}

- (void)processSettingsDidChange
{
	if ([self.file isEqualToString:@"Notification"])
	{
		BOOL isDND = [self.settingsStore boolForKey:@"an_dnd_open"];
		BOOL nightDND = [self.settingsStore boolForKey:@"an_dnd_night"];
		[[APNSManager instance] setDND:isDND nightDND:nightDND];
	}
	else if ([self.file isEqualToString:@"Personal"])
	{
		YAObjUserInfo *userInfo = [[[YAObjUserInfo alloc] init] autorelease];
		
		userInfo.nickname = [self.settingsStore objectForKey:@"details_nickname"];
		userInfo.sex = [self.settingsStore objectForKey:@"details_sex"];
		userInfo.sign = [self.settingsStore objectForKey:@"details_sign"];
		userInfo.location = [self.settingsStore objectForKey:@"details_location_postcode"];
		
		[[UserManager instance] updateUserInfo:userInfo];
	}
}

- (void)reload
{
	[self loadDynamicSettings:YES];
	if (PROCESS_SUPERCLASS_METHOD(IASKAppSettingsViewController, @selector(reload)));
}

- (void)viewWillAppear:(BOOL)animated
{
	[self loadDynamicSettings:NO];
	
	[super viewWillAppear:animated];

	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingDidChange:) name:kIASKAppSettingChanged object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogin:) name:UMUserLoginDidFinishedNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogout:) name:UMUserLogoutDidFinishedNotification object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userInfoUpdate:) name:UMGetUserInfoDidFinishedNotification object:nil];
	
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
	[self processSettingsDidChange];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark kIASKAppSettingChanged notification
- (void)settingDidChange:(NSNotification*)notification
{
	if ([notification.object isEqual:@"an_type_sound"]) {
		[[APNSManager instance] openAPNS];
	}
}

#pragma mark UMUserLoginDidFinishedNotification
- (void)userDidLogin:(NSNotification*)notification
{
	[self reload];
}

#pragma mark UMUserLogoutDidFinishedNotification
- (void)userDidLogout:(NSNotification*)notification
{
	[self reload];
}

#pragma mark UMGetUserInfoDidFinishedNotification
- (void)userInfoUpdate:(NSNotification*)notification
{
	if ([self.file isEqualToString:@"Personal"])
	{
		[self updateUserInfoToSettingStore];
		
		[self reload];
	}
}

#pragma mark - IASKAppSettingsViewControllerDelegate protocol

- (CGFloat)tableView:(UITableView*)tableView heightForSpecifier:(IASKSpecifier*)specifier
{
	if ([specifier.key isEqualToString:@"AboutIcon"])
	{
		return [specifier.defaultStringValue floatValue];
	}
	else
	{
		return tableView.rowHeight;
	}
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForSpecifier:(IASKSpecifier*)specifier
{
	UITableViewCell *cell = nil;
	
	cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:specifier.key];
	
	if (!cell)
	{
		if ([specifier.key isEqualToString:@"details_location"]
			|| [specifier.key isEqualToString:@"app_checkversion"]
			|| [specifier.key isEqualToString:@"details_sex"]
			|| [specifier.key isEqualToString:@"details_sign"])
		{
			cell = [[[IASKPSTitleValueSpecifierViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:specifier.key] autorelease];
			cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		}
		else
		{
			cell = (UITableViewCell*)[[[NSBundle mainBundle] loadNibNamed:specifier.key
																	owner:self
																  options:nil] objectAtIndex:0];
		}
	}
	
	if ([cell isKindOfClass:[IASKPSTitleValueSpecifierViewCell class]])
	{
		cell.textLabel.text = specifier.title;
		NSString *textValue = [self.settingsStore objectForKey:specifier.key];
		if ([specifier.key isEqualToString:@"details_sex"])
		{
			cell.detailTextLabel.text = [SexPickerView titleForValue:textValue];
		}
		else if ([specifier.key isEqualToString:@"details_sign"])
		{
			cell.detailTextLabel.text = [SignPickerView titleForValue:textValue];
		}
		else
		{
			cell.detailTextLabel.text = textValue;
		}

		cell.detailTextLabel.textAlignment = specifier.textAlignment;
		cell.textLabel.adjustsFontSizeToFitWidth = specifier.adjustsFontSizeToFitWidth;
		cell.detailTextLabel.adjustsFontSizeToFitWidth = specifier.adjustsFontSizeToFitWidth;
	}

	return cell;
}

- (void)settingsViewController:(IASKAppSettingsViewController*)sender tableView:(UITableView *)tableView didSelectCustomViewSpecifier:(IASKSpecifier*)specifier
{
	BOOL bCancelSelected = YES;
	
	if ([specifier.key isEqualToString:@"details_location"])
	{
		NSString *postcode = [self.settingsStore objectForKey:@"details_location_postcode"];

		TSLocateView *locateView = [[TSLocateView alloc] initWithPostCode:postcode delegate:sender];
		[locateView showInView:sender.view];
		[locateView release];

	}
	else if ([specifier.key isEqualToString:@"details_sex"])
	{
		id value = [self.settingsStore objectForKey:@"details_sex"];
		
		SexPickerView *pickerView = [[SexPickerView alloc] initWithValue:value delegate:sender];
		
		[pickerView showInView:sender.view];
		
		[pickerView release];
	}
	else if ([specifier.key isEqualToString:@"details_sign"])
	{
		id value = [self.settingsStore objectForKey:@"details_sign"];
		
		SignPickerView *pickerView = [[SignPickerView alloc] initWithValue:value delegate:sender];
		
		[pickerView showInView:sender.view];
		
		[pickerView release];
	}
	else if ([specifier.key isEqualToString:@"app_checkversion"])
	{
		[[UpgradeAlert instance] checkUpgrade];
	}

	if (bCancelSelected)
	{
		NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
		if (indexPath)
		{
			[tableView deselectRowAtIndexPath:indexPath animated:YES];
		}
	}
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 1)
	{
		if ([actionSheet isKindOfClass:[TSLocateView class]])
		{
			TSLocateView *locateView = (TSLocateView *)actionSheet;
			NSString *postcode = locateView.locate.postcode;
			[self.settingsStore setObject:postcode forKey:@"details_location_postcode"];
			
			NSString *display = [self displayLocation:locateView.locate];
			[self.settingsStore setObject:display forKey:@"details_location"];

			[self performSelector:@selector(reload)];
		}
		else if ([actionSheet isKindOfClass:[SexPickerView class]])
		{
			SexPickerView *pickerView = (SexPickerView *)actionSheet;
			[self.settingsStore setObject:pickerView.currentValue forKey:@"details_sex"];
			
			[self performSelector:@selector(reload)];
		}
		else if ([actionSheet isKindOfClass:[SignPickerView class]])
		{
			SignPickerView *pickerView = (SignPickerView *)actionSheet;
			[self.settingsStore setObject:pickerView.currentValue forKey:@"details_sign"];
			
			[self performSelector:@selector(reload)];
		}
	}
}

@end
